<template>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" class="elDiaLog" lock-scroll
		width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">

		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading2">
		
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="150px">
				<el-form-item required label="合同名称" prop="title">
					<el-input v-model="formData.title" placeholder="请输入合同名称" />
				</el-form-item>
				<el-form-item required label="合同编号" prop="contract_no">
					<el-input v-model="formData.contract_no" placeholder="请输入合同编号" />
				</el-form-item>
				<el-form-item required label="签订单位" prop="company">
					<el-input v-model="formData.company" placeholder="请输入签订单位" />
				</el-form-item>
				<el-form-item required label="申请部门" prop="did">
					<el-tree-select 
						v-model="formData.did"
						:data="baseConfigStore.newExDepartmentList"
						check-strictly 
						:render-after-expand="false"
						style="width: 100%" 
						placeholder="请选择申请部门"  >
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
				</el-form-item>
				<el-form-item required label="承办人" prop="uid">
					<el-select v-model="formData.uid" placeholder="请选择承办人" style="width: 100%">
						<el-option v-for="(item, index) in userFList" :key="item.uid" :label="item.name"
							:value="item.uid">
							<treeBlock :dataItem="item" :typeClass="2"></treeBlock>
						</el-option>
					</el-select>

				</el-form-item>
				<el-form-item label="签批人设置" prop="huiqian">
					<div class="elTimeBox">
						<el-button  v-if="approveList.type == 0" type="primary" style="margin-bottom: 20px;"
							@click="clickShenPiR('ac_addlist','huiqian')"><template #icon><i-ep-CirclePlusFilled /></template>增加一级审批</el-button>
						<el-timeline>
							<el-timeline-item v-for="(item,index) in formData.huiqian">
								<template #dot>
									<div class="el-timeline-item__node el-timeline-item__node--large">
										<el-icon><i-ep-user-filled /></el-icon>
									</div>
								</template>
								<div class="levelC">
									<div class="levelT">
										<h2 class="levelTH2" v-if="approveList.type == 0">第{{index + 1}}级会签人审批</h2>
										<h2 class="levelTH2" v-else>{{item.name}}</h2>
										<el-button v-if="index != 0" @click="delectUserClose(index,'huiqian')" circle style="border: none;" >
											<template #icon><i-ep-Delete /></template>
										</el-button>
									</div>
									<div class="levelP">
										<div v-for="(ites,inds) in item.user_info" class="levelPi">
											<div class="levelPiU">
												<div class="levelPiUImgs">
													<img class="levelPiUImg" :src="ites.avatar" alt="">
												</div>
												<div class="levelPiUName">
													{{ites.name}}
												</div>
											</div>
											<div class="levelDelet" @click="closeUser(item,index,inds,'huiqian')">
												<i-ep-close style="width: 14px;" />
											</div>
										</div>
										<div class="levelP_add" >
											<el-button @click="addUser(item,index,'huiqian')" >
												<template #icon><i-ep-CirclePlus /></template>添加
											</el-button>
										</div>
										
									</div>
								</div>
							</el-timeline-item>
						</el-timeline>
					</div>
				</el-form-item>
				<el-form-item label="审核人设置" prop="shenpi">		
					
					<div class="elTimeBox">
						<el-button v-if="approveList2.type == 0" type="primary" style="margin-bottom: 20px;"
							@click="clickShenPiR('ac_addlist','shenpi')"><template #icon><i-ep-CirclePlusFilled /></template>增加一级审批</el-button>
						<el-timeline>
							<el-timeline-item v-for="(item,index) in formData.shenpi">
								<template #dot>
									<div class="el-timeline-item__node el-timeline-item__node--large">
										<el-icon><i-ep-user-filled /></el-icon>
									</div>
								</template>
								<div class="levelC">
									<div class="levelT">
										<h2 class="levelTH2" v-if="approveList2.type == 0">第{{index + 1}}级审核人审批</h2>
										<h2 class="levelTH2" v-else>{{item.name}}</h2>
										
										<el-button v-if="index != 0" @click="delectUserClose(index,'shenpi')" circle style="border: none;" >
											<template #icon><i-ep-Delete /></template>
										</el-button>
									</div>
									<div class="levelP">
										<div v-for="(ites,inds) in item.user_info" class="levelPi">
											<div class="levelPiU">
												<div class="levelPiUImgs">
													<img class="levelPiUImg" :src="ites.avatar" alt="">
												</div>
												<div class="levelPiUName">
													{{ites.name}}
												</div>
											</div>
											<div class="levelDelet" @click="closeUser(item,index,inds,'shenpi')">
												<i-ep-close style="width: 14px;" />
											</div>
										</div>
										<div class="levelP_add" >
											<el-button @click="addUser(item,index,'shenpi')" >
												<template #icon><i-ep-CirclePlus /></template>添加
											</el-button>
										</div>
									</div>
								</div>
							</el-timeline-item>
						</el-timeline>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="['act_info','audit_art'].includes(dialogStatus)" v-loading="loading2">
			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1" 
					label="合同名称：">{{dataInfo.title}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="合同编号：">{{dataInfo.contract_no}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="签订单位：">{{dataInfo.company}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
					label="申请部门：">{{dataInfo.department?.name}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="承办人：">{{dataInfo.user?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
				label="申请时间："><el-text
						type="primary">{{dataInfo.add_time_text}}</el-text></el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
					label="审核状态：">
					<el-tag
						:type="titModel[dataInfo.status]?.type">{{titModel[dataInfo.status]?.title}}</el-tag></el-descriptions-item>
				<el-descriptions-item 
				label-class-name="labelC1" label="会签进度：">
				
				<div class="uTCont" v-for="uItem in dataInfo.huiqian_approve?.rule" style="width: 100%;">
					<h4 class="uThead">{{uItem.name}}</h4>
					<el-table border  :data="uItem.user_info" style="width: 100%">
					<el-table-column label="会签人" width="200">
						<template #default="scope">
							<div class="uhead">
								<el-avatar :size="40" :src="scope.row.avatar" ></el-avatar>
								<span class="uheadN">{{scope.row.name}}</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="会签状态" align="center" width="150">
						<template #default="scope">
							<el-tag v-if="scope.row.status == 0" type="info">待会签</el-tag>
							<el-tag v-if="scope.row.status == 1" type="success">已通过</el-tag>
							<el-tag v-if="scope.row.status == 2" type="danger">已驳回</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作日期" width="220">
						<template #default="scope">
							<el-icon> <el-icon-timer></el-icon-timer></el-icon>
							<span style="margin-left: 10px">{{ scope.row.check_time }}</span>
						</template>
					</el-table-column>
					<el-table-column label="备注">
						<template #default="scope">
							{{ scope.row.mark }}
						</template>
					</el-table-column>
				</el-table> 
				</div>
				
				
				
				
					<!-- <el-table
					v-if="dataInfo.huiqian_approve?.log"
					border 
					:data="dataInfo.huiqian_approve?.log" 
					style="width: 100%">
					 <el-table-column label="操作人" width="150">
					   <template #default="scope">
					     <i class="el-icon-user" />
					     {{ scope.row.user.name }}
					   </template>
					 </el-table-column>
					  <el-table-column label="审核状态" align="center" width="150">
					    <template #default="scope">
							<el-tag  :type="titModel[scope.row.status].type">{{titModel[scope.row.status].title}}</el-tag>
					    </template>
					  </el-table-column>
					  <el-table-column label="备注">
					    <template #default="scope">
					      {{ scope.row.mark }}
					    </template>
					  </el-table-column>
					  <el-table-column label="操作日期" width="220">
					    <template #default="scope">
							<el-icon> <el-icon-timer></el-icon-timer></el-icon>
							<span style="margin-left: 10px">{{ scope.row.check_time_text }}</span>
					    </template>
					  </el-table-column>
					</el-table>
					<span v-else>待会签</span> -->
				</el-descriptions-item>
				

				<el-descriptions-item label-class-name="labelC1" label="审核进度：">
					
					<div class="uTCont" v-if="dataInfo.shenpi_approve" v-for="uItem in dataInfo.shenpi_approve?.rule" style="width: 100%;">
						<h4 class="uThead">{{uItem.name}}</h4>
						<el-table border  :data="uItem.user_info" style="width: 100%">
						<el-table-column label="审批人" width="200">
							<template #default="scope">
								<div class="uhead">
									<el-avatar :size="40" :src="scope.row.avatar" ></el-avatar>
									<span class="uheadN">{{scope.row.name}}</span>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="审核状态" align="center" width="150">
							<template #default="scope">
								<el-tag v-if="scope.row.status == 0" type="info">待审核</el-tag>
								<el-tag v-if="scope.row.status == 1" type="success">已通过</el-tag>
								<el-tag v-if="scope.row.status == 2" type="danger">已驳回</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="操作日期" width="220">
							<template #default="scope">
								<el-icon> <el-icon-timer></el-icon-timer></el-icon>
								<span style="margin-left: 10px">{{ scope.row.check_time }}</span>
							</template>
						</el-table-column>
						<el-table-column label="备注">
							<template #default="scope">
								{{ scope.row.mark }}
							</template>
						</el-table-column>
					</el-table> 
					</div>
					<span v-else>待会签</span>
					
					
					
					<!-- <el-table 
					v-if="dataInfo.shenpi_approve?.log"
					border 
					:data="dataInfo.shenpi_approve?.log" 
					style="width: 100%">
					 <el-table-column label="操作人" width="150">
					   <template #default="scope">
					     <i class="el-icon-user" />
					     {{ scope.row.user.name }}
					   </template>
					 </el-table-column>
					  <el-table-column label="审核状态" align="center" width="150">
					    <template #default="scope">
							<el-tag  :type="titModel[scope.row.status].type">{{titModel[scope.row.status].title}}</el-tag>
					    </template>
					  </el-table-column>
					  <el-table-column label="备注">
					    <template #default="scope">
					      {{ scope.row.mark }}
					    </template>
					  </el-table-column>
					  <el-table-column label="操作日期" width="220">
					    <template #default="scope">
							<el-icon> <el-icon-timer></el-icon-timer></el-icon>
							<span style="margin-left: 10px">{{ scope.row.check_time_text }}</span>
					    </template>
					  </el-table-column>
					</el-table>
				
					<span v-else>待审核</span> -->
				</el-descriptions-item>	
			</el-descriptions>

		</div>
		<div class="form-box" v-if="['Udetail'].includes(dialogStatus)" v-loading="loading2">
			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1" 
					label="合同名称：">{{dataInfo.title}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="合同编号：">{{dataInfo.contract_no}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="签订单位：">{{dataInfo.company}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
					label="申请部门：">{{dataInfo.department?.name}}
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="承办人：">{{dataInfo.user?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
				label="添加时间："><el-text
						type="primary">{{dataInfo.add_time_text}}</el-text></el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" 
					label="状态：">
					<el-tag
						:type="titModel[dataInfo.status]?.type">{{titModel[dataInfo.status]?.title}}</el-tag>
				</el-descriptions-item>
				
			</el-descriptions>
		
		</div>
		
		
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info'].includes(dialogStatus)" :disabled="loading3" @click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" type="primary" :loading="loading3"
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'重新提交':'确 定'}}</el-button>
			
				<el-button v-if="['act_edit','act_add','audit_art'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">取 消</el-button>
			</div>
		</template>

		<!-- 选择审批人信息 -->
		<el-dialog v-model="dialogTree.visible" class="elDiaLog" lock-scroll title="选择审核人" width="1000px"
			@close="closeDialogTree">
			<div style="min-height: 300px;">
				<el-tree ref="treeRef" node-key="id" :data="options" :default-expanded-keys="[1]"
					:check-on-click-node="true" :show-checkbox="true"
					:props="{'children': 'children','label':'name','value':'id','disabled':'disable'}">
					<template #default="{ node, data }">
						<div class="lineDiv">
							<div v-if="data.avatar" class="lineimgs">
								<img class="lineimg" style="width: 20px;height: 20px;" :src="data.avatar" alt="">
							</div>
							<div class="lineTx">
								{{ node.label }}
							</div>
						</div>
					</template>
				</el-tree>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="getAllkeys">确定</el-button>
					<el-button @click="closeDialogTree">取消</el-button>
				</div>
			</template>

		</el-dialog>

	</el-dialog>


</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import { BUSINESS_TYPE } from "@/utils/constant";
	import engineSelect from "./engineSelect.vue"

	import {
		getUserOptions,
	} from "@/api/engine";
	import {
		addContract,
		updataContract,
		getContractDetail,
	} from "@/api/contract";

	//接口地址
	import {
		getDepartmentAndUser
	} from "@/api/doc";

	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		},
		approveList:{
			type:Object,
			default: () => { },
		},
		approveList2:{
			type:Object,
			default: () => { },
		}
	});
	const titModel = ref([{
		title: '待审核',
		type: 'info',
		value: 0
	}, {
		title: '已通过',
		type: 'success',
		value: 1
	}, {
		title: '已驳回',
		type: 'danger',
		value: 2
	}])
	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading2 = ref(false);//新增或者修改加载load按钮
	const loading3 = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dataInfo = ref<any>({});
	const formData = ref<any>({
		id: undefined,
		did: "",//申请部门
		uid: "",//经办人
		title: "",//合同名称
		contract_no: "",//合同编号
		company: "",//签订单位
		huiqian: [[]],//签批人列表
		shenpi: [[]]//审批人列表
	})
	const rules = reactive<any>({
		did: [{ required: true, message: '请选择申请部门', trigger: 'blur' }],
		uid: [{ required: true, message: '请选择经办人', trigger: 'blur' }],
		title: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
		contract_no: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
		company: [{ required: true, message: '请输入签订单位', trigger: 'blur' }],
		huiqian:[{required: true,  validator: userValidator, trigger: "blur"}],
		shenpi:[{required: true,  validator: userValidator2, trigger: "blur"}]
	})
	/**
	 * 审批人校验器
	 */
	function userValidator(rule: any, value: any, callback: any) {
		if (!value || value.length === 0) {
			return callback(new Error("请选择签批人"));
		}
		const hasEmptyValue = value.some(item => item.length === 0);
		if (hasEmptyValue) {
			return callback(new Error("请选择签批人"));
		}
		return callback();
	}
	/**
	 * 审批人校验器
	 */
	function userValidator2(rule: any, value: any, callback: any) {
		if (!value || value.length === 0) {
			return callback(new Error("请选择审核人"));
		}
		const hasEmptyValue = value.some(item => item.length === 0);
		if (hasEmptyValue) {
			return callback(new Error("请选择审核人"));
		}
		return callback();
	}
	watch(
		() => props.dialogTableValue,
		() => {
			if (props.dialogStatus == "audit_art") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_info"  ) {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_edit" ) {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if(props.dialogStatus =="Udetail")
			{
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
			
				formData.value.huiqian = JSON.parse(JSON.stringify(props.approveList.rule));
				formData.value.shenpi = JSON.parse(JSON.stringify(props.approveList2.rule));
				
			}
		}, { deep: true, immediate: true })




	// users: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
	// 提交新增内容/or修改
	function handleSubmit() {
		dataFormRef.value.validate((valid : boolean) => {
			console.log(valid)
			if (valid) {
				loading3.value = true;
				// let huiqian = formData.value.huiqian.map(group => group.map(item => item.uid));
				// let shenpi = formData.value.shenpi.map(group => group.map(item => item.uid));
				const rules:any = []
				for(var i = 0 ; i <formData.value.huiqian.length;i++)
				{
					const item = formData.value.huiqian[i]
					if(props.approveList.type==1)
					{
						rules.push({
							name:item.name,
							type:item.type,
							level:item.level,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
					else
					{
						rules.push({
							name:`第${i + 1}级会签人审批`,
							type:0,
							level:0,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
				}
				const rules2:any = []
				for(var y = 0 ; y <formData.value.shenpi.length;y++)
				{
					const item2 = formData.value.shenpi[y]
					if(props.approveList2.type==1)
					{
						rules2.push({
							name:item2.name,
							type:item2.type,
							level:item2.level,
							user:item2.user_info.map(userObj => userObj.uid)
						})
					}
					else
					{
						rules2.push({
							name:`第${i + 1}级审批人审批`,
							type:0,
							level:0,
							user:item2.user_info.map(userObj => userObj.uid)
						})
					}
				}
				
				
				
				
				let data : any = {
					id: formData.value.id,
					did: formData.value.did,
					uid: formData.value.uid,
					title: formData.value.title,
					contract_no: formData.value.contract_no,
					company: formData.value.company,
					huiqian: rules,
					shenpi: rules2
				}
				if (formData.value.id) {
					ElMessageBox.confirm("重新修提交将重新走审批流程?", "警告", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(() => {
						updataContract(data).then((res) => {
							console.log(res)
							emit('initRefreshList');
							loading3.value = false;
							ElMessage({ message: '修改成功', type: 'success' ,duration:1000})
							closeDialog();
						}).finally(() => {
							loading3.value = false;
						})
					}).catch(() => {
						loading3.value = false;
					});
				}
				else {
					addContract(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '添加成功', type: 'success' ,duration:1000})
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
			}
		});
	}



	// 关闭弹窗
	function closeDialog() {
		if (!loading3.value) {
			emit('update:modelValue', false)
		}
	}

	// 获取详情
	function getAuditDetail(row) {
		loading2.value = true;
		getContractDetail({ id: row.id }).then((res) => {
			let data = res.data;
			dataInfo.value = res.data;
			formData.value.id = res.data.id;
			formData.value.did = res.data.did;
			formData.value.uid = res.data.uid;
			formData.value.title = res.data.title;
			formData.value.contract_no = res.data.contract_no;
			formData.value.company = res.data.company;
			formData.value.huiqian = res.data.huiqian_approve.rule;
			formData.value.shenpi = res.data.shenpi_approve.rule;
			

		}).finally(() => {
			loading2.value = false;
		})
	}



	/**
	 * 添加审批人
	 */
	function clickShenPiR(type : string, el : any, index ?: any) {
		if (type == "ac_delect") {
			formData.value[el].splice(index, 1)
		}
		else if (type == "ac_addlist") {
			formData.value[el].push({name: "",user_info:[]})
		}
	}

	// 审批流相关的代码 start
	const dialogTree = reactive<DialogOption>({
		visible: false,
	});
	const options = ref();
	const defaultUserKey = ref({
		type: "",
		userkey: [],
		index: -1
	});
	const treeRef = ref();
	/**
	 * 打开弹窗添加审批流信息
	 */
	function addUser(e : any, index : number, type : string) {
		console.log(e)
		defaultUserKey.value.userkey = e.user_info.map((item : any) => '1_' + item.uid);
		defaultUserKey.value.type = type;
		defaultUserKey.value.index = index
		dialogTree.visible = true;
		nextTick(() => {
			treeRef.value!.setCheckedKeys(defaultUserKey.value.userkey, false)
		})
	}
	// 删除审批人-组
	function delectUserClose(index:any,type:any){
		const items = formData.value[type];
		if (items.length > 1) {
			items.splice(index, 1);
		}
	}
	/**
	 * 删除审批人
	 */
	function closeUser(e : any, index : number, inds : number, type : string) {
		formData.value[type][index]['user_info'].splice(inds, 1);
	}
	function getAllkeys() {
		formData.value[defaultUserKey.value.type][defaultUserKey.value.index]['user_info'] = treeRef.value!.getCheckedNodes(true);
		closeDialogTree();
	}
	/**
	 * 获取审批人列表
	 */
	function getShenPlist() {
		getDepartmentAndUser().then((res) => {
			options.value = res.data
		}).finally(() => { })
	}
	/**
	* 关闭 树形图 弹窗
	*/
	function closeDialogTree() {
		dialogTree.visible = false;
	}
	// 审批流相关的代码 End
	const userFList : any = ref([]);
	//获取负责人列表
	function getUserOpti(id : any) {
		getUserOptions({ did: id }).then((res) => {
			console.log(res);
			userFList.value = res.data;
			formData.value.uid = findIdInArray(formData.value.uid, userFList.value);

		}).finally(() => { })
	}
	
	// 监听公司数据变化
	watch(() => formData.value.did, (newValue, oldValue) => {
		if (newValue && newValue != oldValue) {
			getUserOpti(newValue);
		}
	});

	function findIdInArray(a : any, b : any) {
		const foundItem = b.find(item => item.uid === a);
		return foundItem ? foundItem.id.toString() : "";
	}

	onMounted(() => {
		getShenPlist();//获取审批人列表
		
	});
</script>

<style lang="scss" scoped>

</style>